<?php
/**
 * Created by PhpStorm.
 * User: Fedax
 * Date: 2018/1/6
 * Time: 19:17
 */

namespace app\admin\controller;

use app\admin\model\AuthAccess;
use app\admin\model\Menu as MenuModel;
use think\Db;
use tree\Tree;
use app\admin\model\OperateLog as GoldEggPrizeLogModel;

class Menu extends Index
{
    protected $rs = '';  //操作纪录日志时使用
    /**
     * 菜单列表
     * @return \think\response\View
     * @throws \think\Exception
     */
    public function index()
    {
        $tree = new Tree();
        $parentId = request()->param("parent_id", 0, 'intval');
        $result = Db::connect('db_manage')->name('Menu')->order('list_order ASC')->select();
        $array = [];
        foreach ($result as $r) {
            $r['selected'] = $r['id'] == $parentId ? 'selected' : '';
            $array[] = $r;
        }
        $str = "<option value='\$id' \$selected>\$spacer \$name</option>";
        $tree->init($array);
        $selectCategory = $tree->getTree(0, $str);
        $this->assign("select_category", $selectCategory);
        return view();
    }

    /**
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function indexData()
    {
        $menuModel = new MenuModel();
        $page_config = array(
            'page' => input('post.offset', 1),
            'list_rows' => input('post.limit', 10),
        );
        $order = input('post.sort', 'list_order') . " " . input('post.order', 'asc');
        $where = array();//组装搜索语句
        if (input('name')) {
            $where[] = ['name', 'like', '%' . input('name') . '%'];
        }
        $data = $menuModel->getDataList($page_config, $where, $order);
        return json($data);
    }
    /**
     * 添加菜单
     * @return \think\response\Json|\think\response\Redirect
     */
    public function add()
    {
        if (request()->isPost()) {

            $goldEggPrizeLogModel = new GoldEggPrizeLogModel(); //纪录日志
            $model = new MenuModel();
            $re = $model->strict(false)->field(true)->insert(input());
            $logData['admin_id'] = session('admin_id');   //纪录日志数据
            $logData['content']  = session('admin_name').'添加了【'.input('name').'】菜单';   //纪录日志数据
            if ($re) {
                $goldEggPrizeLogModel->save($logData);    //将该行为记录在数据库中
                $this->success(lang('add') . lang('success'));
            }
            $this->success(lang('add') . lang('false'));
        }
        return redirect('/Miss');
    }

    /**
     * 编辑菜单
     * @return \think\response\View
     * @throws \think\Exception
     */
    public function edit()
    {
        $tree   = new Tree();
        $id     = input('id',0);
        $menuModel = new MenuModel();
        $rs = $menuModel->where(["id" => $id])->find();
        $this->rs = $rs['name'];  //纪录日志使用
        $result = Db::connect('db_manage')->name('Menu')->order(["list_order" => "ASC"])->select();
        $array  = [];
        foreach ($result as $r) {
            $r['selected'] = $r['id'] == $rs['parent_id'] ? 'selected' : '';
            $array[]       = $r;
        }
        $str = "<option value='\$id' \$selected>\$spacer \$name</option>";

        $tree->init($array);
        $selectCategory = $tree->getTree(0, $str);
        $this->assign("data", $rs);
        $this->assign("select_category", $selectCategory);
        return view();
    }

    /**
     * 后台菜单编辑提交保存
     */
    public function editPost()
    {
        if (request()->isPost()) {

            $model = new MenuModel();
            $goldEggPrizeLogModel = new GoldEggPrizeLogModel();
            $re = $model->strict(false)->field(true)->update(input(''));
            $logData['admin_id'] = session('admin_id');   //纪录日志数据
            $logData['content']  = session('admin_name').'修改了菜单【'.$this->rs.'】为【'.input('name').'】';  //纪录日志数据
            if ($re) {
                $goldEggPrizeLogModel->save($logData);   //将该行为记录在数据库中
                $this->success(lang('edit') . lang('success'));
            }
            $this->success(lang('edit') . lang('false'));
        }
        return redirect('/Miss');
    }

    /**
     * 删除菜单
     * @return \think\response\Redirect
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function del()
    {
        $menuModel = new MenuModel();
        $authAccessModel = new AuthAccess();
        $goldEggPrizeLogModel = new GoldEggPrizeLogModel(); //纪录日志
        $count = $menuModel->where(["parent_id" => input('id')])->count();
        if ($count > 0) {
            $this->error('该菜单下还有子菜单，无法删除！');
        }
        $data=$menuModel->where('id',input('id'))->find();
        $logData['admin_id'] = session('admin_id');    //记录日志数据
        $logData['content']  = session('admin_name').'删除了【'.$data['name'].'】菜单';  //记录日志数据
        if ($menuModel->destroy(input('id')) !== false) {
            $app    = $data['app'];
            $model  = $data['controller'];
            $action = $data['action'];
            $param =  $data['param'];
            $name   = strtolower("$app/$model/$action");
            if ($param) {
                $name = strtolower("$app/$model/$action" . '?' . $param);
            }
            $authAccessModel->where('rule_name',$name)->delete();
            $goldEggPrizeLogModel->save($logData);  //纪录删除日志
            $this->success(lang('delete') . lang('success'));
        } else {
            $this->error(lang('delete') . lang('false'));
        }
        return redirect('/Miss');
    }

    /**
     * 菜单排序
     */
    public function listOrder()
    {
        $adminMenuModel = new MenuModel();
        if(parent::listOrders($adminMenuModel)){
            $this->success(lang('operate') . lang('success'));
        };
        $this->error(lang('operate') . lang('false'));
    }
}